<?php

namespace App\Controllers\Admin;
use Pub;
use Sentry,User,DB,Commodity,Machine,Menu,Cache,Wechat;
use App;
use BaseController,View,Input,Form,Order,Customer,Redirect;
class MenusController extends BaseController {

	/**
	 * Display a listing of the resource.
	 *
	 * @return Response
	 */
	public function index()
	{
		//
        $METHOD = 'accounts';
        $ACTION = 'menus';
        $mymenus = $this->get_data ( );
        return View::make('admin.menus.index',compact('METHOD','ACTION','mymenus'));
	}


	/**
	 * Show the form for creating a new resource.
	 *
	 * @return Response
	 */
	public function create()
	{
		//
        $METHOD = 'accounts';
        $ACTION = 'menus';
        $mymenus = Menu::where('pid','0')->orderBy('pid', 'asc')->orderBy('sort','asc' )->get ();
        return View::make('admin.menus.create',compact('METHOD','ACTION','mymenus'));
	}


	/**
	 * Store a newly created resource in storage.
	 *
	 * @return Response
	 */
	public function store()
	{

        $menu_id = Input::get('menu_id');

        if($menu_id){
            $apply = Menu::find($menu_id);
        }else{
            $apply = new Menu;
        }

        $apply->title = Input::get('title');
        $apply->keyword = Input::get('keyword');
        $apply->url = Input::get('url');
        $apply->pid = Input::get('pid');
        $apply->sort = Input::get('sort');
        $apply->type = Input::get('type');
        $apply->save();

        return Redirect::route('admin.menus.index');

	}


	/**
	 * Display the specified resource.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function show($id)
	{
		//
	}


	/**
	 * Show the form for editing the specified resource.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function edit($id)
	{
		//

        //
        $menu_info = Menu::find($id);
        $METHOD = 'accounts';
        $ACTION = 'menus';
        $mymenus = Menu::where('pid','0')->orderBy('pid', 'asc')->orderBy('sort','asc' )->get ();
        return View::make('admin.menus.edit',compact('METHOD','ACTION','mymenus','menu_info'));
	}


	/**
	 * Update the specified resource in storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function update($id)
	{
		//
        echo $id;
	}


	/**
	 * Remove the specified resource from storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function destroy()
	{
		//
        $id = Input::get('id');
        $menu_info = Menu::destroy($id);
        return Redirect::route('admin.menus.index');
	}


    function get_data() {
        $listobj = Menu::orderBy('pid', 'asc')->orderBy('sort','asc' )->get ();

        $list = array();

        // 转化为数组
        foreach ( $listobj as $k => $vo ) {
            $list[$k]['id'] = $vo->id;
            $list[$k]['url'] = $vo->url;
            $list[$k]['keyword'] = $vo->keyword;
            $list[$k]['type'] = $vo->type;
            $list[$k]['title'] = $vo->title;
            $list[$k]['pid'] = $vo->pid;
            $list[$k]['sort'] = $vo->sort;
            $list[$k]['token'] = $vo->token;
        }

        foreach ( $list as $k => $vo ) {
            if ($vo ['pid'] != 0)
                continue;

            $one_arr [$vo ['id']] = $vo;
            unset ( $list [$k] );
        }

        foreach ( $one_arr as $p ) {
            $data [] = $p;

            $two_arr = array ();
            foreach ( $list as $key => $l ) {
                if ($l ['pid'] != $p ['id'])
                    continue;

                $l ['title'] = '├──' . $l ['title'];
                $two_arr [] = $l;
                unset ( $list [$key] );
            }

            $data = array_merge ( $data, $two_arr );
        }

        return $data;
    }


    function _deal_data($d) {
        $res ['name'] = str_replace ( '├──', '', $d ['title'] );

        if($d ['type'] == 'location') {
            $res ['type'] = 'location_select';

            $res ['key'] = 'rselfmenu_2_0';
        } elseif (! empty ( $d ['keyword'] )) {
            $res ['type'] = 'click';

            $res ['key'] = $d ['keyword'];
        } else {
            $res ['type'] = 'view';
            $res ['url'] = $d ['url'];
        }
        return $res;
    }
    function json_encode_cn($data) {
        $data = json_encode ( $data );
        return preg_replace ( "/\\\u([0-9a-f]{4})/ie", "iconv('UCS-2BE', 'UTF-8', pack('H*', '$1'));", $data );
    }

    // 发送菜单到微信
    function send_menu() {
        $data = $this->get_data ();
        foreach ( $data as $k => $d ) {
            if ($d ['pid'] != 0)
                continue;
            $tree ['button'] [$d ['id']] = $this->_deal_data ( $d );
            unset ( $data [$k] );
        }
        foreach ( $data as $k => $d ) {
            $tree ['button'] [$d ['pid']] ['sub_button'] [] = $this->_deal_data ( $d );
            unset ( $data [$k] );
        }
        $tree2 = array ();
        $tree2 ['button'] = array ();

        foreach ( $tree ['button'] as $k => $d ) {
            $tree2 ['button'] [] = $d;
        }
        $tree = $this->json_encode_cn ( $tree2 );
        $access ['access_token'] = $this->get_token();

        file_get_contents ( 'https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=' . $access ['access_token'] );

        $url = 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token=' . $access ['access_token'];
        $header [] = "content-type: application/x-www-form-urlencoded; charset=UTF-8";

        $ch = curl_init ();
        curl_setopt ( $ch, CURLOPT_URL, $url );
        curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, "POST" );
        curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, FALSE );
        curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, FALSE );
        curl_setopt ( $ch, CURLOPT_HTTPHEADER, $header );
        curl_setopt ( $ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)' );
        curl_setopt ( $ch, CURLOPT_FOLLOWLOCATION, 1 );
        curl_setopt ( $ch, CURLOPT_AUTOREFERER, 1 );
        curl_setopt ( $ch, CURLOPT_POSTFIELDS, $tree );
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
        $res = curl_exec ( $ch );
        curl_close ( $ch );
        $res = json_decode ( $res, true );
        if ($res ['errcode'] == 0) {
            $this->success ( '发送菜单成功' );
        } else {
            $this->success ( '发送菜单失败，错误的返回码是：' . $res ['errcode'] . ', 错误的提示是：' . $res ['errmsg'] );
        }
    }

    public function get_token(){

        $pub = Pub::find(1);


        if (Cache::has('token'))
        {
            //
            $token = Cache::get('token');
        }else{
            $token =  Wechat::get_access_token($pub->AppID,$pub->AppSecret);
            Cache::put('token', $token, 240);
        }

        return $token;
    }
    public function success($text){
        echo $text;
    }
    public function error($text){
        echo $text;
    }

}
